<script setup name="gooddialog">
import { ref } from "vue"
import { toast } from "@/composables/util"
import { getCategoryGoods, deleteCategoryGoods, connectCategoryGoods } from "@/api/category"
import FormDialog from "@/components/FormDialog.vue"
import ChooseGoods from "@/components/ChooseGoods.vue"

// 弹框节点
const dialogRef = ref()
// 分类ID
const category_id = ref(0)
// 表格数据
const tableData = ref([])
// 表格加载状态
const tableLoading = ref(false)
// 商品选择节点
const ChooseGoodsRef = ref()

// 显示弹窗
const open = item => {
  category_id.value = item.id
  getData()
  dialogRef.value.open()
}

// 获取数据
const getData = async () => {
  tableLoading.value = true
  const res = await getCategoryGoods(category_id.value)
  tableLoading.value = false
  tableData.value = res
}
// 关联商品分类
const handleConnect = () => {
  ChooseGoodsRef.value.open(async goods_ids => {
    try {
      dialogRef.value.showLoading()
      await connectCategoryGoods({ category_id: category_id.value, goods_ids })
      getData()
      toast("关联商品操作成功")
    } finally {
      dialogRef.value.hideLoading()
    }
  })
}
// 删除商品分类
const handleDelete = async row => {
  await deleteCategoryGoods(row.id)
  toast("删除成功")
  getData()
}

defineExpose({
  open
})
</script>

<template>
  <FormDialog ref="dialogRef" top="3vh" title="推荐商品" :width="60" confirmText="关联" cancelText="关闭" @submit="handleConnect">
    <el-table :data="tableData" border height="64vh" stripe style="width: 100%" v-loading="tableLoading">
      <el-table-column prop="goods_id" label="ID" width="66" />
      <el-table-column label="商品封面" width="96">
        <template #default="{ row }">
          <el-image :src="row.cover" fit="fill" :lazy="true" style="width: 70px; height: 70px" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column label="操作" width="60" align="center">
        <template #default="{ row }">
          <el-popconfirm width="172" title="是否要删除该记录？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDelete(row)">
            <template #reference>
              <el-icon :size="16">
                <Close />
              </el-icon>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </FormDialog>
  <ChooseGoods ref="ChooseGoodsRef" />
</template>

<style lang="scss" scoped></style>
